<template>
  <div class="app-container">
    <!--搜索区 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      v-show="showSearch"
      :inline="true"
    >
      <el-form-item label="插件名称" prop="roleName">
        <el-input
          v-model="queryParams.roleName"
          placeholder="请输入插件名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="插件类型"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="插件状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!--功能区 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleInstall"
          >安装</el-button
        >
      </el-col>

      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <!--列表展示区 -->
    <el-table
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="插件名称"
        prop="name"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="插件类型"
        prop="type"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="插件主类"
        prop="className"
        width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="插件版本"
        prop="version"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="插件状态" prop="status" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == -1"> 已卸载 </el-tag>
          <el-tag v-if="scope.row.status == 1"> 已启用 </el-tag>
          <el-tag v-if="scope.row.status == 0" type="danger"> 已禁用 </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="开发者"
        prop="developer"
        width="150"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="安装时间"
        align="center"
        prop="installTime"
      ></el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpgrade(scope.row)"
            >升级</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status === 0"
            @click="handleEnabled(scope.row)"
            >启用</el-button
          >
          <el-button
            size="mini"
            type="text"
            style="color: #e6a23c"
            v-if="scope.row.status === 1"
            @click="handleDisabled(scope.row)"
            >禁用</el-button
          >
          <el-button
            size="mini"
            type="text"
            v-if="scope.row.status != -1"
            style="color: #f56c6c"
            @click="handleUnInstall(scope.row)"
            >卸载</el-button
          >
          <el-button size="mini" type="text" @click="handleReduction(scope.row)"
            >还原</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 安装插件对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="插件名称" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入插件名称"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="插件类型" prop="type">
              <el-select v-model="form.type" clearable placeholder="请选择">
                <el-option
                  v-for="item in pluginTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>

        <el-form-item label="插件主类" prop="className">
          <el-input v-model="form.className" placeholder="请输入插件主类" />
        </el-form-item>
        <el-form-item label="插件版本" prop="version">
          <el-input v-model="form.version" placeholder="请输入插件版本" />
        </el-form-item>
        <el-form-item label="插件包">
          <file-upload
            ref="installUpload"
            :action="getUploadUrl('/plugin/install')"
            :limit="1"
            accept=".jar"
            :fileData="form"
            :auto-upload="false"
            @uploadError="installUploadError"
            @uploadSuccess="installUploadSuccess"
          ></file-upload>
        </el-form-item>
        <el-form-item label="开发者" prop="developer">
          <el-input v-model="form.developer" placeholder="请输入开发者" />
        </el-form-item>
        <el-form-item label="使用例子" prop="template">
          <el-input v-model="form.template" placeholder="请输入使用例子" />
        </el-form-item>
        <el-form-item label="插件描述">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入插件描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitInstall"
          :loading="installLoading"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 升级插件对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="upgradeOpen"
      width="500px"
      append-to-body
      :destroy-on-close="true"
    >
      <el-form :model="form" label-width="80px" ref="upgradeForm">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="插件名称" prop="name">
              <el-input
                v-model="form.name"
                disabled
                placeholder="请输入插件名称"
              /> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="插件类型" prop="type">
              <el-select
                disabled
                v-model="form.type"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in pluginTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select> </el-form-item
          ></el-col>
        </el-row>
        <el-form-item label="插件版本" prop="version">
          <el-input v-model="form.version" placeholder="请输入插件版本" />
        </el-form-item>
        <el-form-item label="插件包">
          <file-upload
            ref="upgradeUpload"
            :action="getUploadUrl('/plugin/upgrade')"
            :limit="1"
            accept=".jar"
            :fileData="form"
            :auto-upload="false"
            @uploadError="upgradeUploadError"
            @uploadSuccess="upgradeUploadSuccess"
          ></file-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="upgradeSubmit"
          :loading="upgradeLoading"
          >确 定</el-button
        >
        <el-button @click="cancelUpgrade">取 消</el-button>
      </div>
    </el-dialog>
    <!-- <install :open="open"></install> -->
  </div>
</template>

<script>
import {
  pagePlugin,
  enabledPlugin,
  disabledPlugin,
  unInstallPlugin,
  reductionPlugin,
} from "@/api/plugin/plugin";
import FileUpload from "@/components/FileUpload";

export default {
  name: "Plugin",
  components: {
    FileUpload,
  },
  data() {
    return {
      upgradeOpen: false,
      upgradeLoading: false,
      installLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 插件表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 数据范围选项
      pluginTypes: [
        {
          value: "reader",
          label: "reader",
        },
        {
          value: "writer",
          label: "writer",
        },
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined,
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "插件名称不能为空", trigger: "blur" },
        ],
        type: [
          { required: true, message: "插件类型不能为空", trigger: "blur" },
        ],
        className: [
          { required: true, message: "插件主类不能为空", trigger: "blur" },
        ],
        version: [
          { required: true, message: "插件版本不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    installUploadError() {
      this.installLoading = false;
      this.open = true;
    },
    installUploadSuccess() {
      this.installLoading = false;
      this.open = false;
      this.resetForm("form");
      this.getList();
    },
    upgradeUploadError() {
      this.upgradeLoading = false;
      this.upgradeOpen = true;
    },
    upgradeUploadSuccess() {
      this.upgradeLoading = false;
      this.upgradeOpen = false;
      this.resetForm("upgradeForm");
      this.getList();
    },
    handleUpgrade(row) {
      this.form = row;
      this.upgradeOpen = true;
    },
    cancelUpgrade() {
      this.upgradeOpen = false;
      this.resetForm("upgradeForm");
    },
    upgradeSubmit() {
      this.$refs["upgradeForm"].validate((valid) => {
        if (valid) {
          this.upgradeLoading = true;
          this.$refs.upgradeUpload.submitFile();
        }
      });
    },
    getUploadUrl(url) {
      return process.env.VUE_APP_BASE_API + url;
    },
    handleEnabled(row) {
      this.$confirm("此操作将启用该插件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          enabledPlugin({ id: row.id }).then((res) => {
            this.$message({
              type: "success",
              message: "启用成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    handleDisabled(row) {
      this.$confirm("此操作将禁用该插件,将影响运行任务,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          disabledPlugin({ id: row.id }).then((res) => {
            this.$message({
              type: "success",
              message: "禁用成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    handleUnInstall(row) {
      this.$confirm("此操作将卸载该插件,将影响运行任务,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          unInstallPlugin({ id: row.id }).then((res) => {
            this.$message({
              type: "success",
              message: "卸载成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    handleReduction(row) {
      this.$confirm(
        "此操作将还原上一个版本的插件,将影响运行任务,是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          reductionPlugin({ id: row.id }).then((res) => {
            this.$message({
              type: "success",
              message: "还原成功!",
            });
            this.getList();
          });
        })
        .catch(() => {});
    },
    /** 查询插件列表 */
    getList() {
      this.loading = true;
      pagePlugin(this.addDateRange(this.queryParams, this.dateRange))
        .then((response) => {
          let data = response.data;
          this.roleList = data.records;
          this.total = data.total;
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      (this.menuExpand = false),
        (this.menuNodeAll = false),
        (this.deptExpand = true),
        (this.deptNodeAll = false),
        (this.form = {
          roleId: undefined,
          roleName: undefined,
          roleKey: undefined,
          roleSort: 0,
          status: "0",
          menuIds: [],
          deptIds: [],
          menuCheckStrictly: true,
          remark: undefined,
        });
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    /** 安装按钮操作 */
    handleInstall() {
      this.reset();
      this.open = true;
      this.title = "安装插件";
    },
    /** 提交按钮 */
    submitInstall: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.installLoading = true;
          this.$refs.installUpload.submitFile();
        }
      });
    },
  },
};
</script>
